package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dao.SetmealDao;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetMealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {
    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    public void saveSetMealAndDish(SetmealDto setmealDto) {
        //保存套餐基本属性
        super.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(new Consumer<SetmealDish>() {
            @Override
            public void accept(SetmealDish setmealDish) {
                setmealDish.setSetmealId(setmealDto.getId());
            }
        });
        //保存套餐下菜品
        setMealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeSetMealAndDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //select count(*) from setmeal where id in ids and status = 1
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        //查询完结果
        int count = super.count(setmealLambdaQueryWrapper);

        if (count >0){
            //有正在起售的套餐
            throw new CustomException("有正在售卖的商品，不可以删除");
        }

        //可以删除，先删除套餐，再删除套餐中的关联菜品
        super.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //select * from setmeal_dish where setmeal_dish.(setmeal_id) in 传过来的套餐ids
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setMealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
